﻿/******************************************************************************
 * Copyright (C) 671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef GAME_SERVER_AUTHSESSION_H_
#define GAME_SERVER_AUTHSESSION_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <ctime>
#include <NodeCpp/Macros.h>
#include <NodeCpp/AutoPtr.h>
#include <NodeCpp/ByteBuffer.h>
#include <NodeCpp/LockedQueue.h>
#include <NodeCpp/Crypto/BigNumber.h>
#include <NodeCpp/Crypto/Sha1.h>
#include <NodeCpp/Crypto/SRP6.h>
#include "Shared/Typedef.h"
#include "Shared/WorldPacket.h"
#include "Shared/Common.h"
using NodeCpp::AutoPtr;
using NodeCpp::LockedQueue;
using NodeCpp::ByteBuffer;
using NodeCpp::Crypto::BigNumber;
using NodeCpp::Crypto::Sha1Hash;
using NodeCpp::Crypto::SRP6;

class WorldSocketDelegate;

class AuthSession
{
public:
    AuthSession(WorldSocketDelegate* _Sock);
    ~AuthSession(void);

    /* 发送验证请求包，启动验证流程 */
    void SendAuthChallenge(std::uint32_t _Seed);
    /* 将数据包加入队列 */
    void QueuePacket(WorldPacket* _Packet);
    /* 更新会话，返回false会导致该会话被关闭 */
    bool Update(time_t _Diff);

    bool HandlePacket(WorldPacket*);
    int GetID(void) const { return PeerID_; }

    void HandleAuthSessionAccount(SqlQueryHolder* _Holder);

private:
    bool _HandleAuthSession(WorldPacket& _Pkt);
    void _Uninitialize(void);
    typedef LockedQueue<WorldPacket*> PacketQueue;

    WorldSocketDelegate* Sock_;
    PacketQueue Packets_;
    // 会话是否在运行，设置为false会导致会话被关闭
    bool Running_;

    int PeerID_;
    std::string PeerHost_;
    int PeerPort_;

    time_t UnauthLifeTime_;
    // 会话是否验证成功，验证成功后会创建游戏会话并关闭本会话
    bool Authed_;

    std::uint32_t AccountId_;
    std::uint8_t Digest_[20];
    std::uint32_t ClientSeed_, ID_, Security_;
    std::uint32_t Unk2_;
    std::uint32_t BuiltNumberClient_;
    LocaleConstant Locale_;
    std::string Account_;
    BigNumber v_, s_, g_, N_, K_;
    time_t MuteTime_;

    AutoPtr<WorldPacket> AddonPacket_;
    DISALLOW_COPY_AND_ASSIGN(AuthSession);
};

#endif // GAME_SERVER_AUTHSESSION_H_
